package dao.impl;

import dao.UserDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import pojo.User;
import utils.JdbcUtils;
import java.sql.SQLException;


/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.1 下午 19:31
 */
public class UserDaoimpl implements UserDao {
    @Override
    public User selectUserByName(String username) {
        try {
            QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "SELECT * FROM USER WHERE USERNAME = ? ";
            User user = qr.query(sql, new BeanHandler<User>(User.class), username);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void addUser(User user) {
        try {
            QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
            String sql ="insert into user " +
                    "(uid,username,password,name,email,birthday,sex,state,code) " +
                    "values (?,?,?,?,?,?,?,?,?)";
            qr.update(sql,user.getUid(),user.getUsername(),user.getPassword(),user.getName(),
                    user.getEmail(),user.getBirthday(),
                    user.getSex(),user.getState(),user.getCode());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User findAllByusername(String username) {
        try {
            QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "select * from user where username=?";
            User user = qr.query(sql, new BeanHandler<User>(User.class), username);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User selectUserByCode(String code) {
        try {
            QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
            String  sql = "select * from user where code=?";
            User user = qr.query(sql, new BeanHandler<User>(User.class), code);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateUser(User user) {
        try {
            QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
            String sql =  "update user set state = ? where uid = ? " ;
            qr.update(sql, user.getState(), user.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
